﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using VanTaiBLL;
using VanTaiData;
using VanTaiProperty;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using Roles;

namespace VanTaiTMS.Page
{
    public partial class ke_hoach_dieu_dong : System.Web.UI.Page
    {
        #region[Define]
        private DataTable dtLenhDieuDong;
        private DataTable dtLenhDieuDongCode;
        private DataTable dtCheckTranfer;
        private DataTable dtBoNhiem;
        private DataTable dtChucDanh;
        private DataTable dtDMCont;
        private DataTable dtKhachHang;
        private DataTable dtNhanVien;
        private DataTable dtFillterExport;
        private DataTable dtNoiGiaoHang;
        private DataTable dtNoiNhanHang;

        private DataTable dtFilter;

        private DataTable dtSearch;
        protected string SuggestionList;
        protected string StrAlert = "";
        private DataTable dtAutoComplete;
        private static bool flag = false;


        private TMPlan_TransferOrder_BusinessLogic clsLenhDieuDong = new TMPlan_TransferOrder_BusinessLogic();
        private clsBusiness_TMCommandTransferOrder clsLenhDieuDongCode = new clsBusiness_TMCommandTransferOrder();
        private clsTMVehicleBusiness clsXe = new clsTMVehicleBusiness();
        private clsTMVehicleGroupBusiness clsNhomXe = new clsTMVehicleGroupBusiness();
        private clsTMContBusiness clsDMCont = new clsTMContBusiness();
        private clsTMCustomersBusiness clsDSKhachHang = new clsTMCustomersBusiness();
        private clsTMMemberBusiness clsDMNhanVien = new clsTMMemberBusiness();
        private clsTMDeliveryBusiness clsNoiGiaoHang = new clsTMDeliveryBusiness();
        private clsTMDepartmentBusiness clsDMBPhanPhongBan = new clsTMDepartmentBusiness();
        private TMMAIL_CONFIG_BusinessLogic clsMailConfig = new TMMAIL_CONFIG_BusinessLogic();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermisstion();
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.cmdExportToExcel);
            txtYourMail.ReadOnly = true;
            txtEmailResive.ReadOnly = true;
            LoadDropdownlist();
            Autocomplate();
            if (!IsPostBack)
            {
                BindGridLenhDieuDong();
                BindGridLenhDieuDongExportExcel();
                BindGridSoXe();
                BindGridKhachHang();
                BindGridTaiXe();

                BindGridNoiNhanCont();
                BindGridNoiTraCont();

                BindGridNoiNhanHang();
                BindGridNoiTraHang();

                BindLoaiCont();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            flag = true;
            lbThongBaoLoi.Text = "";
            txtMaDieuDong.Enabled = true;
            ClearTextbox();
            ClearDropdownlist();
            txtMaDieuDong.Text = "QG000" + MaTuDong();
            OpenDialog("#kehoachdieudong");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            txtMaDieuDong.Enabled = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        imgSave.Enabled = true;
                        BindGridLenhdieuDongEdit(Convert.ToInt32(ListViewAll.DataKeys[i].Value.ToString()));
                        OpenDialog("#kehoachdieudong");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkHide != null)
                {
                    if (chkHide.Checked)
                    {
                        try
                        {
                            VanTaiBLL.TMPlan_TransferOrder_BusinessLogic.DeleteTMCommandTransferOrder(int.Parse(ListViewAll.DataKeys[i].Value.ToString()));
                        }
                        catch (Exception ex)
                        {
                            lbThongBaoXoa.Text = ex.ToString();
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert += "<div class='alert alert-warning'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Vui lòng nhập vào từ khoá để tìm kiếm !";
                StrAlert += "</div>";
            }
            else
            {
                Search(txtSearch.Text);
            }
        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            txtTuNgayNgayNhapKho.Text = "";
            txtDenNgayNhapKho.Text = "";
            ClearTextbox();
            BindGridLenhDieuDong();
        }
        protected void cmdFilter_Click(object sender, EventArgs e)
        {
            Fillter(txtTuNgayNgayNhapKho.Text, txtDenNgayNhapKho.Text);
        }
        protected void cmdDuyet_Click(object sender, EventArgs e)
        {
            //-------------------------------------------
            try
            {
                for (int i = 0; i < ListViewAll.Items.Count; i++)
                {
                    CheckBox chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                    if (chkView != null)
                    {
                        if (chkView.Checked)
                        {
                            BindGridLenhdieuDongEdit(Convert.ToInt32(ListViewAll.DataKeys[i].Value.ToString()));
                            lbThongBaoLoiTranfer.Text = "Bạn có muốn chuyển kế hoạch này sang lệnh điều động không !";
                            OpenDialog("#chuyenlenhdieudong");
                            upDatePanelTranfer.Update();
                            cmdTransfer.Visible = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void cmdExport_Click(object sender, EventArgs e)
        {
            OpenDialog("#exporttoexcel");
        }
        protected void cmdFillterExport_Click(object sender, ImageClickEventArgs e)
        {
            FillterExport(txtTuNgayNhapKhoExport.Text, txtDenNgayNhapKhoExport.Text);
        }
        protected void cmdExportToExcel_Click(object sender, EventArgs e)
        {
            if (txtNameReport.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng nhập vào tên tập tin để xuất ra tập tin bảng tính !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            else
            {
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment;filename=" + txtNameReport.Text + ".xls");
                Response.Charset = "";
                Response.ContentType = "application/vnd.xls";
                System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
                PaneViewData.RenderControl(htmlWrite);
                HttpContext.Current.Response.Write(stringWrite.ToString());
                HttpContext.Current.Response.End();
                upDatePanelExportToExcel.Update();
            }
        }
        //---------------button-popup---------------------
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (txtMaDieuDong.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào mã điều động !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtNgayDieuDong.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào ngày điều động !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drSoXe.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn số xe !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drTaiXe.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn tài xế !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drNhomXe.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn nhóm xe !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drKhachHang.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn khách hàng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drLoaiCont.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn loại Cont !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drNoiNhanCont.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn nơi nhận Cont !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drNoiTraCont.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn nơi trả Cont !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drNoiNhanHang.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn nơi nhận hàng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drNoiTraHang.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn nơi trả hàng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            //-------------------------------------
            if (txtMaDieuDong.Text != "" && txtNgayDieuDong.Text != ""
                && drSoXe.SelectedValue.ToString() != "-1"
                && drTaiXe.SelectedValue.ToString() != "-1"
                && drNhomXe.SelectedValue.ToString() != "-1"
                && drKhachHang.SelectedValue.ToString() != "-1"
                && drLoaiCont.SelectedValue.ToString() != "-1"
                && drNoiNhanCont.SelectedValue.ToString() != "-1"
                && drNoiTraCont.SelectedValue.ToString() != "-1"
                && drNoiNhanHang.SelectedValue.ToString() != "-1"
                && drNoiTraHang.SelectedValue.ToString() != "-1"
                )
            {
                Insert();
            }
        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {
            
        }
        protected void cmdTransfer_Click(object sender, EventArgs e)
        {
            try
            {
                VanTaiProperty.clsTMPlan_TransferOrderProperty obj = new clsTMPlan_TransferOrderProperty();
                obj.DommandTransferOrder_ID = int.Parse(lbIdTrans.Text);
                VanTaiBLL.TMPlan_TransferOrder_BusinessLogic.TranferTMCommandTransferOrder(obj);
                lbThongBaoLoiTranfer.Text = "Chuyển thành công mẫu tin !";
                OpenDialog("#chuyenlenhdieudong");
                upDatePanelTranfer.Update();
                cmdTransfer.Visible = false;
                cmdCloseTranfer.Text = "Đóng lại";
            }
            catch (Exception ex)
            {
                lbThongBaoLoiTranfer.Text = ex.ToString();
                OpenDialog("#chuyenlenhdieudong");
                upDatePanelTranfer.Update();
                cmdTransfer.Visible = false;
                cmdCloseTranfer.Text = "Đóng lại";
            }
        }
        protected void cmdCloseTranfer_Click(object sender, EventArgs e)
        {
            CloseDialog("#chuyenlenhdieudong");
        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        protected void ImgXetDuyet_Click(object sender, ImageClickEventArgs e)
        {
            //BrowserNV();
        }
        protected void ImgRefeshDuyet_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void ImgRefeshExport_Click(object sender, ImageClickEventArgs e)
        {
            txtTuNgayNhapKhoExport.Text = "";
            txtDenNgayNhapKhoExport.Text = "";
            BindGridLenhDieuDongExportExcel();
        }
        //-------------list-view-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                txtMaDieuDong.Enabled = false;
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyKeHoachDieuDong, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                if (e.CommandName == "Accept" || e.CommandName == "Accept_A" || e.CommandName == "Accept_B" ||
                    e.CommandName == "Accept_C")
                {
                    if (Edit == false)
                    {
                        imgSave.Enabled = false;
                        ClearDropdownlist();
                        Label lbTrangThai = (Label)e.Item.FindControl("lbDuyet");
                        if (lbTrangThai.Text == "1")
                        {
                            imgSave.Enabled = false;
                            string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                            BindGridLenhdieuDongEdit(int.Parse(SenderId));
                            OpenDialog("#kehoachdieudong");
                            upNewUpdatePanel.Update();
                            imgSave.ToolTip = "Cập nhật";
                            flag = false;
                        }
                        else
                        {
                            imgSave.Enabled = true;
                            string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                            BindGridLenhdieuDongEdit(int.Parse(SenderId));
                            OpenDialog("#kehoachdieudong");
                            upNewUpdatePanel.Update();
                            imgSave.ToolTip = "Cập nhật";
                            flag = false;
                        }
                    }
                    else
                    {
                        imgSave.Enabled = true;
                        ClearDropdownlist();
                        Label lbTrangThai = (Label)e.Item.FindControl("lbDuyet");
                        imgSave.Enabled = true;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridLenhdieuDongEdit(int.Parse(SenderId));
                        OpenDialog("#kehoachdieudong");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                LinkButton linkListName = (LinkButton)e.Item.FindControl("linkListName");
                LinkButton linkListName_A = (LinkButton)e.Item.FindControl("linkListName_A");
                LinkButton linkListName_B = (LinkButton)e.Item.FindControl("linkListName_B");
                LinkButton linkListName_C = (LinkButton)e.Item.FindControl("linkListName_C");

                string _jsDouble1 = ClientScript.GetPostBackClientHyperlink(linkListName, "");
                string _jsDouble2 = ClientScript.GetPostBackClientHyperlink(linkListName_A, "");
                string _jsDouble3 = ClientScript.GetPostBackClientHyperlink(linkListName_B, "");
                string _jsDouble4 = ClientScript.GetPostBackClientHyperlink(linkListName_C, "");

                linkListName.Attributes["ondblclick"] = _jsDouble1;
                linkListName.Attributes["onclick"] = "return false;";

                linkListName_A.Attributes["ondblclick"] = _jsDouble2;
                linkListName_A.Attributes["onclick"] = "return false;";

                linkListName_B.Attributes["ondblclick"] = _jsDouble3;
                linkListName_B.Attributes["onclick"] = "return false;";

                linkListName_C.Attributes["ondblclick"] = _jsDouble4;
                linkListName_C.Attributes["onclick"] = "return false;";
            }
        }
        //-----------pagger-----------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            DataPagerListAll.PageSize = 17;
            BindGridLenhDieuDong();
        }
        //---------Check-all--------------
        protected void chkCheckAll_CheckedChanged(object sender, EventArgs e)
        {

        }
        //---------DropDownlist---------------------
        protected void drTrangThai_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        protected void drSoXe_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearDropdownlist();
            BindGridNhomXe(int.Parse(drSoXe.SelectedValue.ToString()));
        }
        protected void drTaiXe_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
        #endregion

        #region[Function]
        protected void BindGridLenhDieuDong()
        {
            dtLenhDieuDong = clsLenhDieuDong.Search(txtSearch.Text);
            dtFilter = clsLenhDieuDong.TMCommandTransferOrde_Fillter_Date(txtTuNgayNgayNhapKho.Text, txtDenNgayNhapKho.Text);
            if (txtTuNgayNgayNhapKho.Text == "" && txtDenNgayNhapKho.Text == "")
            {
                if (dtLenhDieuDong != null && dtLenhDieuDong.Rows.Count > 0)
                {
                    ListViewAll.DataSource = dtLenhDieuDong;
                    ListViewAll.DataBind();
                    ListViewAll.Visible = true;
                    DataPagerListAll.Visible = true;
                }
                else
                {
                    ListViewAll.Visible = false;
                    DataPagerListAll.Visible = false;
                }
            }
            else
            {
                if (dtFilter != null && dtFilter.Rows.Count > 0)
                {
                    ListViewAll.DataSource = dtFilter;
                    ListViewAll.DataBind();
                    ListViewAll.Visible = true;
                    DataPagerListAll.Visible = true;
                }
            }
        }
        protected void BindGridLenhdieuDongEdit(int id)
        {
            dtLenhDieuDong = clsLenhDieuDong.BindGridTMPlan_TransferOrder_Detail_Edit(id);
            if (dtLenhDieuDong != null && dtLenhDieuDong.Rows.Count > 0)
            {
                lbIdTrans.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_ID"].ToString();
                lbID.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_ID"].ToString();
                lbIDXoa.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_ID"].ToString();
                lbAlias.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Alias"].ToString();
                lbTrangThaiDuyet.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Status_Mem"].ToString();
                txtMaDieuDong.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Alias"].ToString();
                txtNgayDieuDong.Text = Convert.ToDateTime(dtLenhDieuDong.Rows[0]["DommandTransferOrder_Date"]).ToString("dd/MM/yyyy");
                BindGridNhomXe(int.Parse(dtLenhDieuDong.Rows[0]["Vehicle_ID"].ToString()));
                drSoXe.SelectedValue = dtLenhDieuDong.Rows[0]["Vehicle_ID"].ToString();

                drTaiXe.SelectedValue = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Mem_ID"].ToString();
                drNhomXe.SelectedValue = dtLenhDieuDong.Rows[0]["VehicleGroup_Old_ID"].ToString();


                txtSoBooking.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Booking_Number"].ToString();
                txtSoCount.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Cont_Number"].ToString();
                drKhachHang.SelectedValue = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Customers_ID"].ToString();
                drLoaiCont.SelectedValue = dtLenhDieuDong.Rows[0]["Cont_ID"].ToString();

                drNoiNhanCont.SelectedValue = dtLenhDieuDong.Rows[0]["Delivery_ID_REQUEST_CONT"].ToString();
                drNoiTraCont.SelectedValue = dtLenhDieuDong.Rows[0]["Delivery_ID_RESPONE_CONT"].ToString();

                drNoiNhanHang.SelectedValue = dtLenhDieuDong.Rows[0]["Delivery_ID_REQUEST_STOCK"].ToString();
                drNoiTraHang.SelectedValue = dtLenhDieuDong.Rows[0]["Delivery_ID_RESPONE_STOCK"].ToString();

                txtSoKM.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Delivery_KM_Number"].ToString();
                txtSoDau.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Delivery_Oil_Number"].ToString();
                txtYeuCau.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Request"].ToString();
                txtGhiChu.Text = dtLenhDieuDong.Rows[0]["DommandTransferOrder_Note"].ToString();
            }
        }
        protected void BindGridLenhDieuDongExportExcel()
        {
            dtFillterExport = clsLenhDieuDong.TMCommandTransferOrde_Fillter_Date(txtTuNgayNhapKhoExport.Text, txtDenNgayNhapKhoExport.Text);
            dtLenhDieuDong = clsLenhDieuDong.BindGridTMPlan_TransferOrder();
            if (txtTuNgayNhapKhoExport.Text == "" && txtDenNgayNhapKhoExport.Text == "")
            {
                if (dtLenhDieuDong != null && dtLenhDieuDong.Rows.Count > 0)
                {
                    ListViewExportToExcel.DataSource = dtLenhDieuDong;
                    ListViewExportToExcel.DataBind();
                    ListViewExportToExcel.Visible = true;
                }
                else
                {
                    ListViewExportToExcel.Visible = false;
                }
            }
            else
            {
                ListViewExportToExcel.DataSource = dtFillterExport;
                ListViewExportToExcel.DataBind();
                ListViewExportToExcel.Visible = true;
            }
        }
        protected void BindGridSoXe()
        {
            dtBoNhiem = clsXe.BindGirdTMVehicle();
            if (dtBoNhiem != null && dtBoNhiem.Rows.Count > 0)
            {
                drSoXe.DataSource = dtBoNhiem;
                drSoXe.DataTextField = "Vehicle_Number";
                drSoXe.DataValueField = "Vehicle_ID";
                drSoXe.DataBind();
            }
        }
        protected void BindGridNhomXe(int id)
        {
            dtChucDanh = clsXe.BindGirdTMVehicle_Detail_Edit(id);
            if (dtChucDanh != null && dtChucDanh.Rows.Count > 0)
            {
                drNhomXe.DataSource = dtChucDanh;
                drNhomXe.DataTextField = "VehicleGroup_Name";
                drNhomXe.DataValueField = "VehicleGroup_Old_ID";
                drNhomXe.DataBind();
            }
        }
        protected void BindGridTaiXe()
        {
            dtNhanVien = clsDMNhanVien.BindGirdTMMember();
            if (dtNhanVien != null && dtNhanVien.Rows.Count > 0)
            {
                drTaiXe.DataSource = dtNhanVien;
                drTaiXe.DataTextField = "FullNameMem";
                drTaiXe.DataValueField = "Member_ID";
                drTaiXe.DataBind();
            }
        }
        protected void BindGridNoiTraHang()
        {
            dtNoiGiaoHang = clsNoiGiaoHang.BindGirdTMDelivery();
            if (dtNoiGiaoHang != null && dtNoiGiaoHang.Rows.Count > 0)
            {
                drNoiTraHang.DataSource = dtNoiGiaoHang;

                drNoiTraHang.DataBind();
            }
        }
        protected void BindGridNoiNhanHang()
        {
            dtNoiNhanHang = clsNoiGiaoHang.BindGirdTMDelivery();
            if (dtNoiNhanHang != null && dtNoiNhanHang.Rows.Count > 0)
            {
                drNoiNhanHang.DataSource = dtNoiNhanHang;
                drNoiNhanHang.DataBind();
            }
        }

        protected void BindGridNoiNhanCont()
        {
            dtNoiGiaoHang = clsNoiGiaoHang.BindGirdTMDelivery();
            if (dtNoiGiaoHang != null && dtNoiGiaoHang.Rows.Count > 0)
            {
                drNoiNhanCont.DataSource = dtNoiGiaoHang;

                drNoiNhanCont.DataBind();
            }
        }
        protected void BindGridNoiTraCont()
        {
            dtNoiGiaoHang = clsNoiGiaoHang.BindGirdTMDelivery();
            if (dtNoiGiaoHang != null && dtNoiGiaoHang.Rows.Count > 0)
            {
                drNoiTraCont.DataSource = dtNoiGiaoHang;

                drNoiTraCont.DataBind();
            }
        }

        protected void BindLoaiCont()
        {
            dtDMCont = clsDMCont.BindGirdTMCont();
            if (dtDMCont != null && dtDMCont.Rows.Count > 0)
            {
                drLoaiCont.DataSource = dtDMCont;
                drLoaiCont.DataTextField = "Cont_Name";
                drLoaiCont.DataValueField = "Cont_ID";
                drLoaiCont.DataBind();
            }
        }
        protected void BindGridKhachHang()
        {
            dtKhachHang = clsDSKhachHang.BindGirdTMCustomers();
            if (dtKhachHang != null && dtKhachHang.Rows.Count > 0)
            {
                drKhachHang.DataSource = dtKhachHang;
                drKhachHang.DataTextField = "Customers_Name";
                drKhachHang.DataValueField = "Customers_ID";
                drKhachHang.DataBind();
            }
        }

        protected void RefeshAllDropdownlist()
        {
            drSoXe.Items.Clear();
            drSoXe.Items.Add(new ListItem("--Vui lòng chọn số xe--", "-1"));
            BindGridSoXe();
            //----------------------------------------------
            drNhomXe.Items.Clear();
            drNhomXe.Items.Add(new ListItem("--Vui lòng chọn nhóm xe--", "-1"));
            //BindGridNhomXe();
            //----------------------------------------------
            drTaiXe.Items.Clear();
            drTaiXe.Items.Add(new ListItem("--Vui lòng chọn tài xế--", "-1"));
            //BindGridTaiXe();
            //----------------------------------------------
            drKhachHang.Items.Clear();
            drKhachHang.Items.Add(new ListItem("--Vui lòng chọn khách hàng--", "-1"));
            BindGridKhachHang();
            //----------------------------------------------
            drLoaiCont.Items.Clear();
            drLoaiCont.Items.Add(new ListItem("--Vui lòng chọn loại Cont--", "-1"));
            BindLoaiCont();
            //----------------------------------------------
            drNoiNhanCont.Items.Clear();
            drNoiNhanCont.Items.Add(new ListItem("--Vui lòng chọn nơi nhận Cont--", "-1"));
            BindGridNoiNhanCont();
            //-----------------------------------------------
            drNoiTraCont.Items.Clear();
            drNoiTraCont.Items.Add(new ListItem("--Vui lòng chọn nơi trả Cont--", "-1"));
            BindGridNoiTraCont();
            //-----------------------------------------------
            drNoiNhanHang.Items.Clear();
            drNoiNhanHang.Items.Add(new ListItem("--Vui lòng chọn nơi nhận hàng--", "-1"));
            BindGridNoiNhanHang();
            //-----------------------------------------------
            drNoiTraHang.Items.Clear();
            drNoiTraHang.Items.Add(new ListItem("--Vui lòng chọn trả hàng--", "-1"));
            BindGridNoiTraHang();
            //-----------------------------------------------
        }
        protected string CountRecord()
        {
            string data = "";
            dtLenhDieuDong = clsLenhDieuDong.BindGridTMPlan_TransferOrder();
            if (dtLenhDieuDong != null && dtLenhDieuDong.Rows.Count > 0)
            {
                data += "Tổng số dòng: " + dtLenhDieuDong.Rows.Count.ToString() + " / " + dtLenhDieuDong.Rows.Count.ToString();
            }
            return data;
        }
        protected void Insert()
        {
            //Insert
            if (flag)
            {
                InsertLenhDieuDong();
            }
            else//Update
            {
                UpdateLenhDieuDong();
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            dtLenhDieuDong = clsLenhDieuDong.BindGridTMPlan_TransferOrder();
            if (dtLenhDieuDong != null && dtLenhDieuDong.Rows.Count > 0)
            {
                foreach (DataRow dr in dtLenhDieuDong.Rows)
                {
                    if (txtMaDieuDong.Text == dr["DommandTransferOrder_Alias"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected bool CheckInsertTranfer_Add()
        {
            bool kiemtra = false;
            dtCheckTranfer = clsLenhDieuDongCode.BindGridTM_CommandTransferOrder();
            if (dtCheckTranfer != null && dtCheckTranfer.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheckTranfer.Rows)
                {
                    if (txtMaDieuDong.Text == dr["DommandTransferOrder_Alias"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertLenhDieuDong()
        {
            try
            {
                if (CheckInsert())
                {
                    lbThongBaoLoi.Text = "Mã này đã tồn tại trong bảng !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    if (CheckInsertTranfer_Add())
                    {
                        lbThongBaoLoi.Text = "Mã điều động này đã tồn tại ở lệnh điều động !";
                        OpenDialog("#thongbao");
                        updatePanelThongBao.Update();
                    }
                    else
                    {
                        VanTaiProperty.clsTMPlan_TransferOrderProperty obj = new clsTMPlan_TransferOrderProperty();
                        obj.DommandTransferOrder_Alias = txtMaDieuDong.Text;
                        obj.DommandTransferOrder_Date = Convert.ToDateTime(txtNgayDieuDong.Text);
                        obj.DommandTransferOrder_Mem_ID = int.Parse(drTaiXe.SelectedValue.ToString());
                        obj.DommandTransferOrder_Vehicle_ID = Convert.ToInt32(drSoXe.SelectedValue.ToString());
                        obj.DommandTransferOrder_Customers_ID = Convert.ToInt32(drKhachHang.SelectedValue.ToString());
                        obj.DommandTransferOrder_Booking_Number = txtSoBooking.Text;
                        obj.DommandTransferOrder_Cont_Number = txtSoCount.Text;
                        obj.DommandTransferOrder_Delivery_ID_0 = Convert.ToInt32(drNoiNhanCont.SelectedValue.ToString());
                        obj.DommandTransferOrder_Delivery_ID_1 = Convert.ToInt32(drNoiTraCont.SelectedValue.ToString());
                        obj.DommandTransferOrder_Delivery_ID_2 = Convert.ToInt32(drNoiNhanHang.SelectedValue.ToString());
                        obj.DommandTransferOrder_Delivery_ID_3 = Convert.ToInt32(drNoiTraHang.SelectedValue.ToString());
                        obj.DommandTransferOrder_Level_1 = 0;
                        obj.DommandTransferOrder_Level_2 = 0;
                        obj.DommandTransferOrder_Delivery_KM_Number = float.Parse(txtSoKM.Text);
                        obj.DommandTransferOrder_Delivery_Oil_Number = float.Parse(txtSoDau.Text);
                        obj.DommandTransferOrder_Request = txtYeuCau.Text;
                        obj.DommandTransferOrder_Cont_ID = Convert.ToInt32(drLoaiCont.SelectedValue.ToString());
                        obj.DommandTransferOrder_Note = txtGhiChu.Text;
                        obj.DommandTransferOrder_Status_Mem = 0;
                        VanTaiBLL.TMPlan_TransferOrder_BusinessLogic.InsertTMCommandTransferOrde(obj);
                        BindGridLenhDieuDong();
                        lbThongBaoLoi.Text = "Thêm mẫu tin thành công !";
                        OpenDialog("#thongbao");
                        updatePanelThongBao.Update();
                        CountRecord();
                        ClearTextbox();
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void UpdateLenhDieuDong()
        {
            try
            {
                VanTaiProperty.clsTMPlan_TransferOrderProperty obj = new clsTMPlan_TransferOrderProperty();
                obj.DommandTransferOrder_ID = int.Parse(lbID.Text);
                obj.DommandTransferOrder_Alias = txtMaDieuDong.Text;
                obj.DommandTransferOrder_Date = Convert.ToDateTime(txtNgayDieuDong.Text);
                obj.DommandTransferOrder_Mem_ID = int.Parse(drTaiXe.SelectedValue.ToString());
                obj.DommandTransferOrder_Vehicle_ID = Convert.ToInt32(drSoXe.SelectedValue.ToString());
                obj.DommandTransferOrder_Customers_ID = Convert.ToInt32(drKhachHang.SelectedValue.ToString());
                obj.DommandTransferOrder_Booking_Number = txtSoBooking.Text;
                obj.DommandTransferOrder_Cont_Number = txtSoCount.Text;
                obj.DommandTransferOrder_Delivery_ID_0 = Convert.ToInt32(drNoiNhanCont.SelectedValue.ToString());
                obj.DommandTransferOrder_Delivery_ID_1 = Convert.ToInt32(drNoiTraCont.SelectedValue.ToString());
                obj.DommandTransferOrder_Delivery_ID_2 = Convert.ToInt32(drNoiNhanHang.SelectedValue.ToString());
                obj.DommandTransferOrder_Delivery_ID_3 = Convert.ToInt32(drNoiTraHang.SelectedValue.ToString());
                obj.DommandTransferOrder_Level_1 = 0;
                obj.DommandTransferOrder_Level_2 = 0;
                obj.DommandTransferOrder_Delivery_KM_Number = float.Parse(txtSoKM.Text);
                obj.DommandTransferOrder_Delivery_Oil_Number = float.Parse(txtSoDau.Text);
                obj.DommandTransferOrder_Request = txtYeuCau.Text;
                obj.DommandTransferOrder_Cont_ID = Convert.ToInt32(drLoaiCont.SelectedValue.ToString());
                obj.DommandTransferOrder_Note = txtGhiChu.Text;
                obj.DommandTransferOrder_Status_Mem = 0;
                VanTaiBLL.TMPlan_TransferOrder_BusinessLogic.UpdateTMCommandTransferOrde(obj);
                BindGridLenhDieuDong();
                lbThongBaoLoi.Text = "Cập nhật mẫu tin thành công !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
                BindGridLenhdieuDongEdit(int.Parse(lbID.Text));
                CountRecord();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        //AutoComplate
        protected void Autocomplate()
        {
            dtAutoComplete = clsLenhDieuDong.BindGridTMPlan_TransferOrder();
            if (dtAutoComplete != null && dtAutoComplete.Rows.Count > 0)
            {
                foreach (DataRow dr in dtAutoComplete.Rows)
                {
                    if (string.IsNullOrEmpty(SuggestionList))
                    {
                        SuggestionList += "\"" + dr["FullNameMem"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["Vehicle_Number"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["DommandTransferOrder_Alias"].ToString().Replace("\n", " ") + "\",";
                    }
                    else
                    {
                        SuggestionList += "\"" + dr["FullNameMem"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["Vehicle_Number"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["DommandTransferOrder_Alias"].ToString().Replace("\n", " ") + "\",";
                    }
                }
            }
        }
        protected void Search(string keywords)
        {
            dtSearch = clsLenhDieuDong.Search(keywords);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtSearch;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + dtSearch.Rows.Count.ToString() + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }
        protected void Fillter(string DateBegin, string EndBegin)
        {
            dtFilter = clsLenhDieuDong.TMCommandTransferOrde_Fillter_Date(txtTuNgayNgayNhapKho.Text, txtDenNgayNhapKho.Text);
            if (dtFilter != null && dtFilter.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtFilter;
                ListViewAll.DataBind();

                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + dtFilter.Rows.Count.ToString() + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }
        protected void FillterExport(string DateBegin, string EndBegin)
        {
            dtFillterExport = clsLenhDieuDong.TMCommandTransferOrde_Fillter_Date(txtTuNgayNhapKhoExport.Text, txtDenNgayNhapKhoExport.Text);
            if (dtFillterExport != null && dtFillterExport.Rows.Count > 0)
            {
                ListViewExportToExcel.DataSource = dtFillterExport;
                ListViewExportToExcel.DataBind();
                ListViewExportToExcel.Visible = true;

                lbThongBaoLoi.Text = "Tìm được " + dtFillterExport.Rows.Count + " lệnh điều động !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();

            }
            else
            {
                ListViewExportToExcel.Visible = false;
                lbThongBaoLoi.Text = "Không tìm được lệnh điều động nào !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }

        #endregion

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        private void CloseDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        #endregion

        #region[ClearTextBox]
        protected void ClearTextbox()
        {
            txtMaDieuDong.Text = "LĐĐ000" + MaTuDong();
            txtSoBooking.Text = "";
            txtSoCount.Text = "";
            txtSoKM.Text = "0";
            txtSoDau.Text = "0";
            txtYeuCau.Text = "";
            txtGhiChu.Text = "";

            drSoXe.SelectedIndex = -1;
            drTaiXe.SelectedIndex = -1;
            drNhomXe.SelectedIndex = -1;
            drKhachHang.SelectedIndex = -1;
            drLoaiCont.SelectedIndex = -1;
            drNoiNhanCont.SelectedIndex = -1;
            drNoiTraCont.SelectedIndex = -1;
            drNoiNhanHang.SelectedIndex = -1;
            drNoiTraHang.SelectedIndex = -1;
        }
        #endregion

        #region[ClearDropdownlist]
        protected void ClearDropdownlist()
        {
            drNhomXe.Items.Clear();
            drNhomXe.Items.Add(new ListItem("--Vui lòng chọn nhóm xe--", "-1"));
        }
        #endregion

        #region[TaoMaTuTong]
        protected int MaTuDong()
        {
            int i = 0;
            dtLenhDieuDongCode = clsLenhDieuDongCode.BindGridTM_CommandTransferOrder();
            if (dtLenhDieuDongCode != null && dtLenhDieuDongCode.Rows.Count > 0)
            {
                int max = Convert.ToInt32(dtLenhDieuDongCode.Rows[0]["DommandTransferOrder_ID"].ToString());
                for (i = 0; i < dtLenhDieuDongCode.Rows.Count; i++)
                {
                    if (int.Parse(dtLenhDieuDongCode.Rows[i]["DommandTransferOrder_ID"].ToString()) > max)
                    {
                        max = Convert.ToInt32(dtLenhDieuDongCode.Rows[i]["DommandTransferOrder_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            return i;
        }
        #endregion

        #region[LoadDropdownlist]
        protected void LoadDropdownlist()
        {
            drNoiTraHang.DataTextField = "Delivery_Name";
            drNoiTraHang.DataValueField = "Delivery_ID";

            drNoiNhanHang.DataTextField = "Delivery_Name";
            drNoiNhanHang.DataValueField = "Delivery_ID";

            drNoiNhanCont.DataTextField = "Delivery_Name";
            drNoiNhanCont.DataValueField = "Delivery_ID";

            drNoiTraCont.DataTextField = "Delivery_Name";
            drNoiTraCont.DataValueField = "Delivery_ID";
        }
        #endregion

        #region[Permisstion]
        protected void CheckPermisstion()
        {
            HttpCookie cookie = Request.Cookies["UserLogin"];
            if (cookie != null)
            {
                bool Is_Page_All = SecurityServices.HasPermisstionPage(StringContent.QuanLyKeHoachDieuDong, int.Parse(cookie["RolesID"]), true);
                if (Is_Page_All == true)
                {
                    bool AddNew = SecurityServices.HasPermisstion(StringContent.QuanLyKeHoachDieuDong, int.Parse(cookie["RolesID"]), TypeaAudit.AddNew);
                    if (AddNew == false)
                    {
                        cmdAddNew.Visible = false;
                    }
                    else
                    {
                        cmdAddNew.Visible = true;
                    }
                    bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyKeHoachDieuDong, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                    if (Edit == false)
                    {
                        cmdEdit.Visible = false;
                    }
                    else
                    {
                        cmdEdit.Visible = true;
                    }
                    bool Del = SecurityServices.HasPermisstion(StringContent.QuanLyKeHoachDieuDong, int.Parse(cookie["RolesID"]), TypeaAudit.Delete);
                    if (Del == false)
                    {
                        cmdDel.Visible = false;
                    }
                    else
                    {
                        cmdDel.Visible = true;
                    }
                }
                else
                {
                    Response.Redirect("error-page.aspx");
                }
            }
        }
        #endregion
    }
}